<?php

namespace app\common\mqtt;

use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\Exceptions\MqttClientException;
use think\Config;
use think\Log;

class MqttPublisher
{
    private $mqtt;

    public function __construct()
    {
        $config = Config::get('mqtt');

        $this->mqtt = new MqttClient($config['server'], $config['port'], $config['client_id']);

        $connectionSettings = (new ConnectionSettings)
            ->setUsername($config['username'])
            ->setPassword($config['password'])
            ->setKeepAliveInterval(60);

        try {
            $this->mqtt->connect($connectionSettings, true);
            Log::info('Connected to MQTT broker.');
        } catch (MqttClientException $e) {
            Log::error('连接失败: ' . $e->getMessage());
            throw $e;
        }
    }



    public  function publishMessage($deviceId, $params)
    {
        $topic = "ZHZN/{$deviceId}";
        try {
            $this->mqtt->publish($topic, json_encode($params), 0);
            Log::info("Message published to topic {$topic}: " . json_encode($params));
            return ['status' => 'success', 'message' => 'Message published successfully.'];
        } catch (MqttClientException $e) {
            Log::error('MQTT publish error: ' . $e->getMessage());
            return ['status' => 'error', 'message' => 'Error publishing message: ' . $e->getMessage()];
        }
    }


    public function __destruct()
    {
        if ($this->mqtt !== null) {
            $this->mqtt->disconnect();
            Log::info('Disconnected from MQTT broker.');
        }
    }
}